<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root">
        <div>
            <div>
                <p>{{name}}</p>
                <p>{{sex}}</p>
            </div>
        </div>
        <p>{{old}}</p>
        <p>{{like}}</p>
    </div>
    <script>

        const tmpNode = document.querySelector("#root")
        // 克隆一个节点,保存生成的节点
        const tmpNode2 = tmpNode.cloneNode(tmpNode)


        let data = {
            name: "张三",
            sex: "男",
            old: 18,
            like: "run"
        }
    
        function compileTemplate(dom, data) {
            const regRule = /\{\{(.+?)\}\}/g

            // 获取所有节点包括子节点
            const childNodes = dom.childNodes

            for (let i = 0; i < childNodes.length; i++) {
                let type = childNodes[i].nodeType  // 3为文本，1为节点
                if (type === 3) {

                    // 获取节点的值
                    let txt = childNodes[i].nodeValue
                    // // 此时可以进行数据替换
                    txt = txt.replace(regRule, (a,b,c) => {
                        return data[b]
                    })

                    childNodes[i].nodeValue = txt 

                } else if (type === 1) {
                    compileTemplate(childNodes[i], data)
                }
            }
    
        } 
    
        compileTemplate(tmpNode2, data)

        root.parentNode.replaceChild(tmpNode2, root)
    </script>

</body>


</html>